package com.sakura.demo.common.exception;

import com.sakura.demo.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    //捕获校验异常
    //结果返回状态码(400错误)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    //该方法用来处理非法参数异常
    public Result handler(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        ObjectError error = result.getAllErrors().stream().findFirst().get();
        log.error("数据校验异常:----{}", error.getDefaultMessage());
        return Result.fail(error.getDefaultMessage());
    }


    //结果返回状态码(400错误)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    //该方法用来处理非法参数异常
    public Result handler(IllegalArgumentException e) {
        log.error("参数异常:----{}", e.getMessage());
        return Result.fail(e.getMessage());
    }

    //结果返回状态码(400错误)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    //该方法用来处理Runtime异常
    public Result handler(RuntimeException e) {
        log.error("Runtime异常:----{}", e.getMessage());
        return Result.fail(e.getMessage());
    }
}
